package com.crux.config.exception;


import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import lombok.Data;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class SentinelException  implements BlockRequestHandler {

    @Override
    public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
        if(throwable instanceof DegradeException){
            return ServerResponse.status(HttpStatus.OK)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(new CurrentDegradeResponse()));
        }else if (throwable instanceof ParamFlowException){
            return ServerResponse.status(HttpStatus.OK)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(new CurrentLimitingResponse()));
        }else{
            return ServerResponse.status(HttpStatus.OK)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(new CurrentUnpredictableResponse()));
        }

    }

}
@Data
class CurrentLimitingResponse{
    private String status = "200001";
    private String code = "系统繁忙";
}

@Data
class CurrentDegradeResponse{
    private String status = "200002";
    private String code = "系统熔断";
}

@Data
class CurrentUnpredictableResponse{
    private String status = "200008";
    private String code = "系统异常";
}